package service;

import dao.ArticleDao;
import model.Article;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;

import java.util.List;

public class ArticleService {
    private ArticleDao articleDao = new ArticleDao();
    private Parser parser = Parser.builder().build();
    private HtmlRenderer renderer = HtmlRenderer.builder().build();

    /**
     * 发布新文章
     */
    public boolean publish(String title, String content, int userId) {
        return articleDao.insert(title, content, userId);
    }
    /**
     * 获取所有文章列表
     */
    public List<Article> getAll() {
        return articleDao.getAll();
    }

    /**
     * 获取文章详情
     */
    public Article getArticleDetail(int articleId) {
        Article article = articleDao.getById(articleId);
        if (article != null) {
            // 将Markdown转换为HTML
            String markdown = article.getContentMarkdown();
            Node document = parser.parse(markdown);
            String htmlContent = renderer.render(document);
            article.setContentHtml(htmlContent);
        }
        return article;
    }
    
    /**
     * 删除文章
     */
    public boolean deleteArticle(int articleId, int userId) {
        // 首先检查文章是否存在且属于当前用户
        if (!articleDao.isArticleOwnedByUser(articleId, userId)) {
            return false;
        }
        
        // 执行删除操作
        return articleDao.deleteById(articleId);
    }
    
    /**
     * 检查文章是否属于指定用户
     */
    public boolean isArticleOwnedByUser(int articleId, int userId) {
        return articleDao.isArticleOwnedByUser(articleId, userId);
    }
}